package com.citcc.api.netty.utils;

public class Crc16Util {
	public static int crc16(byte[] bytes) {
		int crc = 0xFFFF;
		for (int j = 0; j < bytes.length; j++) {
			crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
			crc ^= (bytes[j] & 0xff);// byte to int, trunc sign
			crc ^= ((crc & 0xff) >> 4);
			crc ^= (crc << 12) & 0xffff;
			crc ^= ((crc & 0xFF) << 5) & 0xffff;
		}
		crc &= 0xffff;
		return crc;
	}

	public static String strForCrc16(byte Pushdata[], int length) {

		int Reg_CRC = 0xffff;
		int temp;
		int i, j;
		for (i = 0; i < length; i++) {

			temp = Pushdata[i];
			if (temp < 0)
				temp += 256;
			temp &= 0xff;
			Reg_CRC ^= temp;

			for (j = 0; j < 8; j++) {
				if ((Reg_CRC & 0x0001) == 0x0001)
					Reg_CRC = (Reg_CRC >> 1) ^ 0xA001;
				else
					Reg_CRC >>= 1;
			}
		}
		// 不足四位补0
		String c = Integer.toHexString((Reg_CRC & 0xffff));
		if (c.length() == 3) {
			c = "0" + c;
		} else if (c.length() == 2) {
			c = "00" + c;
		} else if (c.length() == 1) {
			c = "000" + c;
		}
		return c;
	}
	
	
	
	public static String Make_CRC(byte[] data) {
        byte[] buf = new byte[data.length];// 存储需要产生校验码的数据
        for (int i = 0; i < data.length; i++) {
            buf[i] = data[i];
        }
        int len = buf.length;
        int crc = 0xFFFF;//16位
        for (int pos = 0; pos < len; pos++) {
            if (buf[pos] < 0) {
                crc ^= (int) buf[pos] + 256; // XOR byte into least sig. byte of
                                                // crc
            } else {
                crc ^= (int) buf[pos]; // XOR byte into least sig. byte of crc
            }
            for (int i = 8; i != 0; i--) { // Loop over each bit
                if ((crc & 0x0001) != 0) { // If the LSB is set
                    crc >>= 1; // Shift right and XOR 0xA001
                    crc ^= 0xA001;
                } else
                    // Else LSB is not set
                    crc >>= 1; // Just shift right
            }
        }
        String c = Integer.toHexString(crc);
        if (c.length() == 4) {
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 3) {
            c = "0" + c;
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 2) {
            c = "0" + c.substring(1, 2) + "0" + c.substring(0, 1);
        }
        return c;
    }

	
	//Byte by[] ={0x81};
}
